package com.chlitina.store.modules.inventory.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.DateUtils;
import com.chlitina.store.common.utils.StoreProductUtils;
import com.chlitina.store.common.utils.StringUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.base.service.CustomerService;
import com.chlitina.store.modules.base.service.StoreCareService;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.base.service.StoreSelfProductService;
import com.chlitina.store.modules.cash.web.Types;
import com.chlitina.store.modules.employee.dao.EmployeeDao;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.expert.service.ProductService;
import com.chlitina.store.modules.inventory.dao.InventoryInDao;
import com.chlitina.store.modules.inventory.entity.StoreInventoryIn;
import com.chlitina.store.modules.inventory.entity.StoreInventoryInDetail;
import com.chlitina.store.modules.inventory.model.InProduct;
import com.chlitina.store.modules.inventory.model.InQuery;
import com.chlitina.store.modules.inventory.model.InventoryIn;
import com.chlitina.store.modules.inventory.service.InventoryService;
import com.chlitina.store.modules.sms.utils.SMSSend1;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * Inventory Controller
 * 
 * @author Songsong.xu
 * @version 2013-11-05
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/inventory/in")
public class InventoryInController extends BaseController {
	@Autowired
	private ProductService productService;
	@Autowired
	private StoreCareService storeCareService;
	@Autowired
	private StoreProductService storeProductService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private InventoryInDao inventoryInDao;
	@Autowired
	private InventoryService inventoryService;
	@Autowired
	private StoreSelfProductService storeSelfProductService;
	public static int DEFAULT_PAGE_SIZE = 5;
	String KEY_INVENTORY_IN = "inventoryIn";
	String KEY_IN_PRODUCT = "inProduct";
	String KEY_RED_CODE="InventoryRedVerifyCode";

	String URI_IN_STORE_PRODUCT_ADD_EDIT_PAGE = "modules/inventory/inAddEditStoreProductPage";
	String URI_IN_SYSTEM_PRODUCT_ADD_EDIT_PAGE = "modules/inventory/inAddEditSystemProductPage";

	@RequestMapping(value = { "" })
	public String inventoryIn(InQuery inQuery, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		request.getSession().removeAttribute(KEY_INVENTORY_IN);
		updateEmployee(request);
		// 重新入库,或者
		Page<StoreInventoryIn> page = new Page<StoreInventoryIn>(request,
				response);
		inventoryService.inQuery(page, inQuery);
		model.addAttribute("page", page);
		return "modules/inventory/inventoryIn";
	}

	@ResponseBody
	@RequestMapping(value = { "checkRedVerifyCode" })
	public String checkRedVerifyCode(HttpServletRequest request,
			HttpServletResponse response, Model model, String verifyCode) {
		response.setContentType("application/json; charset=UTF-8");
		List<String> result = new ArrayList<String>();
		Object verify_Code = StoreUtils.getCache(KEY_RED_CODE);
		if (verify_Code == null) {
			result.add("false");
			result.add("状态丢失");
		} else {
			if (verify_Code.equals(verifyCode)) {
				result.add("true");
				result.add("验证通过");
			} else {
				result.add("false");
				result.add("验证失败");
			}
		}
		return JsonMapper.getInstance().toJson(result);
	}

	@ResponseBody
	@RequestMapping(value = { "resendRedVerifyCode" })
	public String resendRedVerifyCode(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		response.setContentType("application/json; charset=UTF-8");
		List<String> result = new ArrayList<String>();
		String verifyCode = StringUtils.generateVerifyCode();
		StringBuilder sb = new StringBuilder();
		sb.append("您本次冲红的校验码为").append(verifyCode)
				.append(", 请勿向任何人提供您收到的短信校验码");
		StoreUtils.putCache(KEY_RED_CODE,verifyCode);
		boolean state = false;
		String send = null;
		try {
			send = SMSSend1.send(StoreUtils.getStore().getBossMobile(),
					sb.toString());
			System.err.println(send);
			state = true;
		} catch (Exception e) {
			e.printStackTrace();
		}

		result.add(state + "");
		result.add(verifyCode);
		return result.toString();
	}

	@ResponseBody
	@RequestMapping(value = { "red" })
	public String inventoryInRed(InQuery inQuery, HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		response.setContentType("application/json; charset=UTF-8");
		String targetID = request.getParameter("id");
		if (targetID == null || targetID.isEmpty()) {
			return getDirectURL("");
		}
		int target = Integer.valueOf(targetID);
		String result = inventoryService.inventoryInRed(target);
		Map<String, String> map = Maps.newHashMap();
		if ("".equals(result)) {
			map.put("result", "true");
		} else {
			map.put("result", "false");
			map.put("msg", result);
		}
		return JsonMapper.getInstance().toJson(map);
	}

	String getDirectURL(String uri) {
		return "redirect:" + Global.ADMIN_PATH + "/inventory/in/" + uri;
	}

	public void updateEmployee(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object attribute = session.getAttribute("employees");
		if (attribute == null) {
			session.setAttribute("employees", employeeDao.findListByStore(
					StoreUtils.getStore().getId(), Employee.STATUS_WORKING));
		} else if (attribute instanceof List<?>) {
			List<?> a = (List<?>) attribute;
			if (a.size() == 0) {
				session.setAttribute("employees", employeeDao.findListByStore(
						StoreUtils.getStore().getId(), Employee.STATUS_WORKING));
			}
		}
	}

	@RequestMapping(value = { "create" })
	public String inventoryInCreate(InventoryIn inventoryIn, InQuery inQuery,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		// 重新入库
		request.getSession().setAttribute(KEY_INVENTORY_IN, inventoryIn);
		String parameter = request.getParameter("inventoryType");
		inventoryIn.setDateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		model.addAttribute(KEY_INVENTORY_IN, inventoryIn);
		if ("system".equals(parameter)) {
			inventoryIn.setSystemProduct(true);
		} else {
			inventoryIn.setSystemProduct(false);
		}
		return getDirectURL("product/page");
	}

	@ResponseBody
	@RequestMapping(value = { "productData" })
	public String clientLoadingProduct(HttpServletRequest request,
			HttpServletResponse response, String type) {
		List<StoreProduct> storeProducts = null;
		if (Types.system.equalsIgnoreCase(type)) {
			storeProducts = storeProductService
					.findByStatus(StoreProduct.TYPE_SYS, -1);
		} else if (Types.storeself.equalsIgnoreCase(type)) {
			storeProducts = storeProductService
					.findByStatus(StoreProduct.TYPE_SELF, -1);
		} else {
		}
		List<Map<String, Object>> set = Lists.newArrayList();
		Map<String, Object> map = null;
		if (storeProducts != null) {
			for (StoreProduct storeProduct : storeProducts) {
				map = Maps.newHashMap();
				map.put("id", storeProduct.getId());
				map.put("amount", storeProduct.getAmount());
				map.put("category", StoreProductUtils.getCategory(storeProduct));
				map.put("name", StoreProductUtils.getName(storeProduct));
				map.put("retailPrice",
						StoreProductUtils.getRetailPrice(storeProduct));
				map.put("spec", StoreProductUtils.getSpec(storeProduct));
				set.add(map);
			}
		}
		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@RequestMapping(value = { "product/page" })
	public String inProductPage(InQuery inQuery, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Object attribute = request.getSession().getAttribute(KEY_INVENTORY_IN);
		InventoryIn inventoryIn = (InventoryIn) attribute;
		model.addAttribute(KEY_INVENTORY_IN, inventoryIn);
		return getURI_in_system();
	}

	@RequestMapping(value = { "product/cancel" })
	public String inventoryInProductCancel(InQuery inQuery,
			HttpServletRequest request, HttpServletResponse response,
			Model model, RedirectAttributes redirectAttributes) {
		Object attribute = request.getSession().getAttribute(KEY_INVENTORY_IN);
		if (attribute != null) {// Multiples to cancel same one
			request.getSession().removeAttribute(KEY_INVENTORY_IN);
		}
		return getDirectURL("");
	}

	@RequestMapping(value = "product/save")
	public String inventoryInProductSave(InQuery inQuery,
			HttpServletRequest request, HttpServletResponse response,
			Model model, RedirectAttributes redirectAttributes) {
		Object attribute = request.getSession().getAttribute(KEY_INVENTORY_IN);
		if (attribute == null) {
			addMessage(redirectAttributes, "状态丢失");
			return getDirectURL("");
		}
		InventoryIn saved = (InventoryIn) attribute;
		String jsonData = request.getParameter("products");
		saved.setProducts(jsonData);
		JSONArray jsonArray = JSONArray.fromObject(jsonData);
		JSONObject object = null;
		long id = 0;
		int amount = 0;
		List<InProduct> systemProducts = saved.getProductList();
		for (int i = 0; i < jsonArray.size(); i++) {
			object = (JSONObject) jsonArray.get(i);
			id = object.getLong("id");
			amount = object.getInt("amount");
			InProduct p = new InProduct();
			p.setProduct(storeProductService.get(id));
			p.setAmount(amount);
			systemProducts.add(p);
		}

		String parameter = request.getParameter("employee.id");
		saved.getEmployee().setId(Long.parseLong(parameter));
		String remark = request.getParameter("remark");
		saved.setRemark(remark);
		StoreInventoryIn inventoryIn = inventoryService.in(saved);
		request.getSession().removeAttribute(KEY_INVENTORY_IN);

		return getDirectURL("detail?id=" + inventoryIn.getId().intValue());
	}

	@RequestMapping(value = { "detail" })
	public String inventoryInDetail(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		String id = request.getParameter("id");
		try {
			long parseInt = Integer.parseInt(id);
			// search details
			StoreInventoryIn inventoryIn = inventoryInDao.findOne(parseInt);
			List<StoreInventoryInDetail> details = inventoryService
					.findDetails((int) parseInt);
			model.addAttribute("details", details);
			model.addAttribute("inventoryIn", inventoryIn);
			return "modules/inventory/inventoryInDetail";
		} catch (Exception e) {
			addMessage(redirectAttributes, "错误的出库查询请求");
			return getDirectURL("");
		}
	}

	String getURI_out_main() {
		return "modules/inventory/inventoryOutMain";
	}

	String getURI_in_system() {
		return "modules/inventory/inventoryInSystem";
	}

	@RequestMapping(value = { "query" })
	public String inventoryInQuery(InQuery inQuery, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return inventoryIn(inQuery, request, response, model);
	}
}
